package com.haixiaoke.saas.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.oss.OssService;
import com.haixiaoke.saas.common.weChat.domain.WeChatLoginParam;
import com.haixiaoke.saas.user.mapper.UserConsumerMapper;
import com.haixiaoke.saas.user.service.IUserConsumerService;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.user.domain.UserConsumer;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * C端用户Service业务层处理
 *
 * @author panda
 * @date 2024-04-11
 */
@Slf4j
@Service
public class UserConsumerServiceImpl implements IUserConsumerService {

    @Autowired
    private UserConsumerMapper userConsumerMapper;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private OssService ossService;

    /**
     * 查询C端用户
     *
     * @param userId C端用户主键
     * @return C端用户
     */
    @Override
    public UserConsumer selectUserConsumerByUserId(Long userId) {
        return userConsumerMapper.selectUserConsumerByUserId(userId);
    }

    /**
     * 查询C端用户列表
     *
     * @param userConsumer C端用户
     * @return C端用户
     */
    @Override
    public List<UserConsumer> selectUserConsumerList(UserConsumer userConsumer) {
        return userConsumerMapper.selectUserConsumerList(userConsumer);
    }

    /**
     * 新增C端用户
     *
     * @param userConsumer C端用户
     * @return 结果
     */
    @Override
    public int insertUserConsumer(UserConsumer userConsumer) {
        userConsumer.setCreateTime(DateUtils.getNowDate());
        return userConsumerMapper.insertUserConsumer(userConsumer);
    }

    /**
     * 修改C端用户
     *
     * @param userConsumer C端用户
     * @return 结果
     */
    @Override
    public int updateUserConsumer(UserConsumer userConsumer) {
        if (ObjectUtil.isEmpty(userConsumer.getUserId())) {
            throw new ServiceException("用户数据异常");
        }
        UserConsumer consumer = userConsumerMapper.selectUserConsumerByUserId(userConsumer.getUserId());
        if (StrUtil.isNotBlank(userConsumer.getProfilePhoto()) && StrUtil.isNotBlank(consumer.getProfilePhoto()) && !StrUtil.equals(userConsumer.getProfilePhoto(), consumer.getProfilePhoto())) {
            ossService.delete(consumer.getProfilePhoto());
        }
        userConsumer.setUpdateTime(DateUtils.getNowDate());
        return userConsumerMapper.updateUserConsumer(userConsumer);
    }

    /**
     * 批量删除C端用户
     *
     * @param userIds 需要删除的C端用户主键
     * @return 结果
     */
    @Override
    public int deleteUserConsumerByUserIds(Long[] userIds) {
        return userConsumerMapper.deleteUserConsumerByUserIds(userIds);
    }

    /**
     * 删除C端用户信息
     *
     * @param userId C端用户主键
     * @return 结果
     */
    @Override
    public int deleteUserConsumerByUserId(Long userId) {
        return userConsumerMapper.deleteUserConsumerByUserId(userId);
    }

    @Override
    public UserConsumer selectUserConsumerByUser(String username, String password) {
        return userConsumerMapper.selectUserConsumerByUser(username, password);
    }

    @Override
    @Transactional
    public UserConsumer weChatSelectUserByPhone(WeChatLoginParam loginParam) {
        String code = loginParam.getCode();
        String encryptedData = loginParam.getEncryptedData();
        String iv = loginParam.getIv();

        WxMaJscode2SessionResult session = null;
        try {
            session = wxMaService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            throw new ServiceException("登录异常：" + e.getLocalizedMessage());
        }
        String openid = session.getOpenid();

        String sessionKey = session.getSessionKey();
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
        String phoneNumber = phoneNoInfo.getPhoneNumber();
        if (StrUtil.isBlank(phoneNumber)) {
            throw new ServiceException("手机号码为空");
        }
        UserConsumer userConsumer = userConsumerMapper.selectUserConsumerByMobile(phoneNumber);
        if (ObjectUtil.isEmpty(userConsumer)) {
            UserConsumer newConsumer = new UserConsumer();
            newConsumer.setUserMobile(phoneNumber);
            newConsumer.setOpenId(openid);
            newConsumer.setCreateTime(DateUtils.getNowDate());
            userConsumerMapper.insertUserConsumer(newConsumer);
            return newConsumer;
        } else {
            userConsumer.setOpenId(openid);
            userConsumer.setUpdateTime(DateUtils.getNowDate());
            userConsumerMapper.updateUserConsumer(userConsumer);
            return userConsumer;
        }
    }

    @Override
    public List<UserConsumer> selectProprietorInfo() {
        return userConsumerMapper.selectProprietorInfo();
    }

    @Override
    public UserConsumer selectUserConsumerByMobileAndPwd(String mobile, String pwd) {
        return userConsumerMapper.selectUserConsumerByMobileAndPwd(mobile, pwd);
    }

    @Override
    public UserConsumer selectUserConsumerByMobile(String phone) {
        return userConsumerMapper.selectUserConsumerByMobile(phone);
    }
}
